#pragma once
#include <string>
#include <signal.h>
#include <functional>
#include "Socket.h"

class Server
{
public:
    using func_t = std::function<void(int)>;//指定别名

public:
    Server(const uint16_t &port, func_t func): _port(port),_func(func)
    {
        _listensock = sock.Socket();//创建
        sock.Bind(_listensock, _port);//绑定
        sock.Listen(_listensock);//监听
    }

    void Start()//执行任务
    {
        signal(SIGCHLD, SIG_IGN);
        while(true)
        {
            std::string clientIp;
            uint16_t clientPort = 0;
            int sockfd = sock.Accept(_listensock,&clientPort,&clientIp);
            if(sockfd < 0) continue;
            if(fork() == 0)
            {
                close(_listensock);
                _func(sockfd);
                close(sockfd);
                exit(0);
            }
            close(sockfd);
        }
    }
    ~Server()  
    {
        if(_listensock >= 0) close(_listensock);
    }
private:
    uint16_t _port;
    int _listensock;
    Sock sock;
    func_t _func;
};